<template>
  <div class="record-container">
    <el-tabs v-model="activeTab" type="line">
      <el-tab-pane label="回款计划" name="paymentPlan">
        <!-- 搜索和筛选控件 -->
        <!-- 企业名称 -->
        <el-card class="filter-card">
          <el-form :inline="true" :model="queryParams" class="demoFormInline">
            <el-form-item label="企业名称">
              <el-input
                v-model="queryParams.companyName"
                placeholder="请输入企业名称"
                clearable
                style="width: 220px"
                @keyup.enter.native="handleSearch"
              />
            </el-form-item>
            <el-form-item label="载体">
              <el-select
                v-model="queryParams.zt"
                placeholder="请选择载体"
                clearable
                style="width: 200px"
              >
                <el-option label="联健元和" value="联健元和" />
                <el-option label="达博" value="达博" />
                <el-option label="科澜项目" value="科澜项目" />
                <el-option label="国科项目" value="国科项目" />
                <el-option label="黄埭项目" value="黄埭项目" />
                <el-option label="金扶梯" value="金扶梯" />
                <el-option label="北联新翼" value="北联新翼" />
                <el-option label="深圳项目" value="深圳项目" />
                <el-option label="西山项目" value="西山项目" />
                <el-option label="秦淮项目" value="秦淮项目" />
                <el-option label="双创中心" value="双创中心" />
                <el-option label="创界项目" value="创界项目" />
                <el-option label="江环项目" value="江环项目" />
                <el-option label="江北项目" value="江北项目" />
                <el-option label="拓展项目" value="拓展项目" />
                <el-option label="试点项目" value="试点项目" />
              </el-select>
            </el-form-item>
            <el-form-item label="应缴费年月">
              <el-date-picker
                v-model="queryParams.startTime"
                type="month"
                placeholder="请选择年月"
                format="YYYY年MM月"
                value-format="YYYY年MM月"
              />
            </el-form-item>
            <el-form-item label="费用类型">
              <el-select
                v-model="queryParams.type"
                placeholder="请选择费用类型"
                clearable
                style="width: 220px"
              >
                <el-option label="租金" value="租金" />
                <el-option label="物业费" value="物业费" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 数据表格 -->
        <el-card class="list-card" style="margin-top: 18px">
          <el-table :data="tableData" border style="width: 100%" v-loading="loading">
            <el-table-column
              prop="companyName"
              label="所属公司"
              width="320"
              show-overflow-tooltip
              align="left"
            />
            <el-table-column prop="cycle" label="缴费周期" width="300" align="left" />
            <el-table-column
              prop="startTime"
              label="应缴费用时间"
              width="150"
              align="left"
            />
            <el-table-column prop="amount" label="总金额" width="120" align="left" />
            <el-table-column
              prop="remainingAmount"
              label="剩余金额"
              width="120"
              align="left"
            />
            <el-table-column
              prop="paidAmount"
              label="已付金额"
              width="120"
              align="left"
            />
            <el-table-column prop="type" label="费用类型" width="100" align="left" />
            <el-table-column
              prop="contractNumber"
              label="合同编号"
              width="320"
              show-overflow-tooltip
              align="left"
            />
            <el-table-column prop="unitPrice" label="单价" width="200" align="left" />
            <el-table-column prop="statusDesc" label="状态" width="200" align="left" />
            <el-table-column
              prop="monthPrice"
              label="月度费用"
              width="100"
              align="left"
            />

            <el-table-column
              prop="remake"
              label="备注"
              width="350"
              show-overflow-tooltip
              align="left"
            />

            <!-- 添加操作列 -->
            <el-table-column label="操作" width="180" fixed="right" align="left">
              <template #default="{ row }">
                <!-- <el-button type="primary" link @click="handlePayment(row)"
                  >缴费</el-button
                > -->

                <el-button type="primary" link @click="viewCompanyProfile(row.companyId)">
                  查看企业档案
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total > 0"
            :total="total"
            :page="queryParams.pageNum"
            :limit="queryParams.pageSize"
            @pagination="handlePagination"
          />
        </el-card>

        <!-- 分页组件 -->
      </el-tab-pane>

      <el-tab-pane label="回款明细" name="paymentLog">
        <!-- 搜索和筛选控件 -->
        <el-card class="filter-card">
          <el-form :inline="true" :model="logQueryParams" class="demoFormInline">
            <!-- 企业名称 -->
            <el-form-item label="企业名称">
              <el-input
                v-model="logQueryParams.companyName"
                placeholder="请输入企业名称"
                clearable
                style="width: 220px"
                @keyup.enter.native="handleSearch"
              />
            </el-form-item>
            <el-form-item label="缴费时间">
              <el-date-picker
                v-model="logQueryParams.createTime"
                type="date"
                placeholder="请选择缴费时间"
                format="YYYY年MM月DD日"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleLogSearch">搜索</el-button>
              <el-button @click="resetLogForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <el-card class="list-card" style="margin-top: 18px">
          <el-table
            :data="logTableData"
            border
            style="width: 100%"
            v-loading="logLoading"
          >
            <el-table-column prop="id" label="Id" width="80" align="left" />

            <el-table-column
              prop="companyName"
              label="缴费企业"
              width="300"
              align="left"
            />

            <el-table-column prop="planId" label="计划ID" width="100" align="left" />
            <el-table-column prop="historyId" label="流水ID" width="100" align="left" />
            <el-table-column prop="amount" label="缴费金额" align="left" />
            <el-table-column prop="createTime" label="缴费时间" align="left" />
            <el-table-column prop="updateTime" label="修改时间" align="left" />
            <el-table-column prop="remark" label="备注" align="left" />

            <!-- <el-table-column label="操作" width="150">
              <template #default="{ row }">
                <el-button type="primary" link>查看详情</el-button>
              </template>
            </el-table-column> -->
          </el-table>

          <!-- 回款明细分页组件 -->
          <pagination
            v-show="logTotal > 0"
            :total="logTotal"
            :page="logQueryParams.pageNum"
            :limit="logQueryParams.pageSize"
            @pagination="handleLogPagination"
          />
        </el-card>
      </el-tab-pane>
    </el-tabs>
    <PaymentModal
      v-model="showPaymentModal"
      :company-id="currentCompanyId"
      :plan-id="currentPlanId"
      @success="handlePaymentSuccess"
      @close="handlePaymentClose"
    />
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, watch } from "vue";
import { getPaymentPlanList, payment_logList } from "@/api/company/info";
import { useRouter } from "vue-router";

// 当前激活的tab
const activeTab = ref("paymentPlan");

// 回款计划查询参数
const queryParams = reactive({
  startTime: getCurrentMonth(),
  companyName: "",
  zt: "",
  type: "",
  pageNum: 1,
  pageSize: 10,
});

// 回款明细查询参数
const logQueryParams = reactive({
  createTime: "",
  companyName: "",
  pageNum: 1,
  pageSize: 10,
});
import PaymentModal from "@/views/PaymentModal.vue";

// 缴费弹窗相关
const showPaymentModal = ref(false);
const currentCompanyId = ref("");
const currentPlanId = ref("");

// 处理缴费操作
function handlePayment(row) {
  currentCompanyId.value = row.companyId;
  currentPlanId.value = row.id;
  showPaymentModal.value = true;
}

// 缴费成功回调
function handlePaymentSuccess() {
  // 重新刷新列表
  fetchData();
  // 关闭弹窗组件
  showPaymentModal.value = false;
}

// 关闭弹窗回调
function handlePaymentClose() {
  // 关闭弹窗组件
  showPaymentModal.value = false;
}
// 回款计划表格数据
const tableData = ref([]);
// 回款计划分页信息
const total = ref(0);
// 回款计划加载状态
const loading = ref(false);

// 回款明细表格数据
const logTableData = ref([]);
// 回款明细分页信息
const logTotal = ref(0);
// 回款明细加载状态
const logLoading = ref(false);

// 添加路由实例
const router = useRouter();

// 获取回款计划数据
const fetchData = async () => {
  loading.value = true;
  try {
    const res = await getPaymentPlanList(queryParams);
    if (res && res.code == 200) {
      // 防御性处理，确保rows为数组
      let rows = [];
      if (Array.isArray(res.rows)) {
        rows = res.rows;
      } else if (
        res.rows &&
        typeof res.rows === "object" &&
        typeof res.rows.length === "number"
      ) {
        rows = Array.from(res.rows);
      }
      tableData.value = rows;
      total.value = res.total || 0;
    } else {
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error("获取回款计划列表失败:", error);
    tableData.value = [];
    total.value = 0;
  } finally {
    setTimeout(() => {
      loading.value = false;
    }, 300);
  }
};

// 获取回款明细数据
const fetchLogData = async () => {
  logLoading.value = true;
  try {
    // 转换日期格式：将 "YYYY-MM-DD" 转换为 "YYYY-MM-DDTHH:mm:ss" 格式，以匹配后端的 LocalDateTime
    const params = { ...logQueryParams };
    if (params.createTime) {
      params.createTime = params.createTime + " 00:00:00";
    }
    const res = await payment_logList(params);
    if (res && res.code == 200) {
      // 防御性处理，确保rows为数组
      let rows = [];
      if (Array.isArray(res.rows)) {
        rows = res.rows;
      } else if (
        res.rows &&
        typeof res.rows === "object" &&
        typeof res.rows.length === "number"
      ) {
        rows = Array.from(res.rows);
      }
      logTableData.value = rows;
      logTotal.value = res.total || 0;
    } else {
      logTableData.value = [];
      logTotal.value = 0;
    }
    logLoading.value = false;
  } catch (error) {
    console.error("获取回款明细列表失败:", error);
    logTableData.value = [];
    logTotal.value = 0;
    logLoading.value = false;
  } finally {
    setTimeout(() => {
      loading.value = false;
    }, 300);
  }
};

// 回款计划搜索
const handleSearch = () => {
  queryParams.pageNum = 1;
  fetchData();
};

// 回款明细搜索
const handleLogSearch = () => {
  logQueryParams.pageNum = 1;
  fetchLogData();
};

// 重置回款计划表单
const resetForm = () => {
  // 重置查询参数
  Object.assign(queryParams, {
    startTime: getCurrentMonth(),
    companyName: "",
    zt: "",
    type: "",
    pageNum: 1,
    pageSize: 10,
  });
  fetchData();
};

// 重置回款明细表单
const resetLogForm = () => {
  // 重置查询参数
  Object.assign(logQueryParams, {
    createTime: "",
    companyName: "",
    pageNum: 1,
    pageSize: 10,
  });
  fetchLogData();
};

// 回款计划分页处理
const handlePagination = ({ page, limit }) => {
  queryParams.pageNum = page;
  queryParams.pageSize = limit;
  fetchData();
};

// 回款明细分页处理
const handleLogPagination = ({ page, limit }) => {
  logQueryParams.pageNum = page;
  logQueryParams.pageSize = limit;
  fetchLogData();
};

// 查看企业档案
const viewCompanyProfile = (companyId) => {
  router.push({
    path: "/lookCompany",
    query: { companyId },
  });
};

// 监听tab切换
watch(activeTab, (newVal) => {
  if (newVal === "paymentPlan") {
    fetchData();
  } else if (newVal === "paymentLog") {
    fetchLogData();
  }
});

// 获取当前月份（格式：YYYY年MM月）
function getCurrentMonth() {
  const now = new Date();
  const year = now.getFullYear();
  const month = (now.getMonth() + 1).toString().padStart(2, "0");
  return `${year}年${month}月`;
}

// 组件挂载时获取数据
onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.paymentPlanContainer {
  padding: 20px;
}

.searchBox {
  margin-bottom: 20px;
}

.tableContainer {
  margin-bottom: 20px;
}
</style>
